package com.pzl.vca;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;

import java.io.IOException;
import java.nio.ByteBuffer;

//视频流解码
public class PlayLiveDecodec {

    private static final String TAG = "jinx_videochatA";
    private static PlayLiveDecodec instance;
    private MediaCodec mediaCodec;

    private PlayLiveDecodec() {
    }

    public static PlayLiveDecodec getInstance() {
        if (instance == null) instance = new PlayLiveDecodec();
        return instance;
    }

    public void initDecoder(Surface surface, int width, int height) {

        try {
            //H265
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_HEVC);
            final MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, width, height);
            //比特率
            format.setInteger(MediaFormat.KEY_BIT_RATE, width * height);
            //帧率
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
            //关键帧I帧的频率，每5秒一个I帧
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
            mediaCodec.configure(format,
                    surface,
                    null, 0);
            mediaCodec.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void decodingRender(byte[] data) {
        Log.i(TAG, "解码渲染  size =  " + data.length);
        int index = mediaCodec.dequeueInputBuffer(100000);
        if (index >= 0) {
            ByteBuffer inputBuffer = mediaCodec.getInputBuffer(index);
            inputBuffer.clear();
            inputBuffer.put(data, 0, data.length);
            //dsp芯片解码    解码的传进去的   只需要保证编码顺序就好了
            mediaCodec.queueInputBuffer(index,
                    0, data.length, System.currentTimeMillis(), 0);
        }
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 100000);
        while (outputBufferIndex >= 0) {
            mediaCodec.releaseOutputBuffer(outputBufferIndex, true);
            outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
        }
    }


}
